package com.yoke.controller.order;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.common.JsonMessage;
import com.yoke.common.base.NginxBaseControl;
import com.yoke.service.order.OrderService;
import com.yoke.service.order.ProductService;
import com.yoke.system.log.SystemLog;
import com.yoke.util.FileUtil;
import com.yoke.util.JsonUtil;
import com.yoke.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Iterator;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * Created by jiangzeyin on 2017/5/15.
 */
@Controller
@RequestMapping("order")
public class EditKhControl extends NginxBaseControl {

    @Resource
    private OrderService orderService;

    @RequestMapping(value = "add.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String index() {
        return "order/add_kh";
    }

    /**
     * @param id id
     * @return s
     * @throws Exception e
     */
    @RequestMapping(value = "edit.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String edit(String id) throws Exception {
        String filePath = orderService.getCustomerInfoFile().getPath();// getOrderUserConfFile();
        id = StringUtil.convertNULL(id);
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String id_ = jsonObject.getString("id");
            if (id.equals(id_)) {
                request.setAttribute("item", jsonObject);
                return "order/add_kh";
            }
        }
        return "order/add_kh";
    }

    @RequestMapping(value = "chang", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String chang(String id, String to) throws IOException {
        final String[] tip = new String[1];
        boolean flag = doItem(id, (array, index, iterable, item) -> {
            int sort = 0;
            if ("up".endsWith(to)) {
                if (index <= 0) {
                    tip[0] = "已经在最上面啦";
                    return;
                }
                sort = array.getJSONObject(index - 1).getIntValue("sort") - 1;
            } else if ("down".equals(to)) {
                if (index == array.size() - 1) {
                    tip[0] = "已经在最底部啦";
                    return;
                }
                sort = array.getJSONObject(index + 1).getIntValue("sort") + 1;
            }
            item.put("sort", sort);
        });
        if (tip[0] != null)
            return JsonMessage.getString(405, tip[0]);
        if (flag)
            return JsonMessage.getString(200, "ok");
        return JsonMessage.getString(400, "保存失败");
    }

    private boolean doItem(String id, DoInfo doInfo) throws IOException {
        id = StringUtil.convertNULL(id);
        String filePath = orderService.getCustomerInfoFile().getPath();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        JSONArray newsJson = new JSONArray();
        {
            Iterator<Object> iterable = jsonArray.iterator();
            while (iterable.hasNext()) {
                JSONObject jsonObject = (JSONObject) iterable.next();
                String parent = jsonObject.getString("parent");
                if (!userName.equals(parent))
                    continue;
                iterable.remove();
                newsJson.add(jsonObject);
            }
        }
        ProductService.sort(newsJson);
        boolean flag = false;
        int count = -1;
        Iterator<Object> newsIterator = newsJson.iterator();
        while (newsIterator.hasNext()) {
            JSONObject jsonObject = (JSONObject) newsIterator.next();
            count++;
            String id_ = jsonObject.getString("id");
            if (id.equals(id_)) {
                doInfo.doIn(newsJson, count, newsIterator, jsonObject);
                flag = true;
                break;
            }
        }
        if (newsJson.size() > 0)
            jsonArray.addAll(newsJson);
        if (flag) {
            String newsJsonStr = JsonUtil.formatJson(jsonArray.toString());
            FileUtil.writeFile(filePath, newsJsonStr);
        }
        return flag;
    }

    private interface DoInfo {
        void doIn(JSONArray jsonArray, int index, Iterator<Object> iterable, JSONObject item);
    }

    /**
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "del_{id}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String del_(@PathVariable String id) throws Exception {
//        id = StringUtil.convertNULL(id);
//        String filePath = orderService.getCustomerInfoFile().getPath();
//        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
//        Iterator<Object> iterable = jsonArray.iterator();
//        int count = jsonArray.size();
        final JSONObject[] delObj = {null};
//        while (iterable.hasNext()) {
//            JSONObject jsonObject = (JSONObject) iterable.next();
//            String parent = jsonObject.getString("parent");
//            if (!userName.equals(parent))
//                continue;
//            String id_ = jsonObject.getString("id");
//            if (id.equals(id_)) {
//
//                break;
//            }
//        }
        boolean flag = doItem(id, (array, index, iterable, item) -> {
            delObj[0] = item;
            iterable.remove();
        });
        if (!flag)
            return JsonMessage.getString(400, "删除失败");
        SystemLog.LOG().info("成功删除客户：" + delObj[0]);
        return JsonMessage.getString(200, "删除成功");

    }


    @RequestMapping(value = "save_kh.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_kh(String id, String pwd, String mark) throws Exception {
        String filePath = orderService.getCustomerInfoFile().getPath();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        Iterator<Object> iterable = jsonArray.iterator();
        String newPwd = null;
        if (!StringUtil.IsEmpty(pwd)) {
            if (StringUtil.IsEmpty(pwd, 6, 20))
                return JsonMessage.getString(400, "请输入6-20的位的密码");
            else
                newPwd = pwd;
        }
        while (iterable.hasNext()) {
            JSONObject jsonObject = (JSONObject) iterable.next();
            String parent = jsonObject.getString("parent");
            if (!userName.equals(parent))
                continue;
            String id_ = jsonObject.getString("id");
            if (id.equals(id_)) {
                jsonObject.put("mark", mark);
                if (newPwd != null)
                    jsonObject.put("pwd", newPwd);
                break;
            }
        }
        String newsJson = JsonUtil.formatJson(jsonArray.toString());
        FileUtil.writeFile(filePath, newsJson);
        return JsonMessage.getString(200, "修改成功");
    }

    @RequestMapping(value = "add_kh.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String add_kh(String name, String pwd, String mark) throws Exception {
        if (StringUtil.IsEmpty(name, 4, 20))
            return JsonMessage.getString(400, "请输入4-20的登录名");
        if (!Pattern.matches("^[0-9a-zA-Z_]+$", name))
            return JsonMessage.getString(400, "客户名只能是数字,字母或者 '_'");
        if (StringUtil.IsEmpty(pwd, 6, 20))
            return JsonMessage.getString(400, "请输入6-20的位的密码");
        if (name.contains("-"))
            return JsonMessage.getString(401, "客户名不能包含中划线");
        String filePath = orderService.getCustomerInfoFile().getPath();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String userName = jsonObject.getString("name");
            if (name.equalsIgnoreCase(userName)) {
                return JsonMessage.getString(400, "已经存在相同的登录名");
            }
        }
        // 过滤-
        name = name.replace('-', '_');
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("pwd", pwd);
        jsonObject.put("mark", mark);
        jsonObject.put("parent", userName);
        String uId = UUID.randomUUID().toString();
        jsonObject.put("id", uId);
        jsonArray.add(jsonObject);
        String newsJson = JsonUtil.formatJson(jsonArray.toString());
        FileUtil.writeFile(filePath, newsJson);
        SystemLog.LOG().info(name + "客户的uid：" + uId);
        return JsonMessage.getString(200, "添加成功");
    }


}
